package cn.boyu.service.impl;

import cn.boyu.entity.AssetsAmmeter;
import cn.boyu.entity.Gather;
import cn.boyu.entity.GatherAmmeter;
import cn.boyu.exception.LogicException;
import cn.boyu.mapper.GatherAmmeterMapper;
import cn.boyu.service.IAssetsAmmeterService;
import cn.boyu.service.IGatherAmmeterService;
import cn.boyu.service.IGatherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yn
 * @since 2022-11-22
 */
@Service
public class GatherAmmeterServiceImpl extends ServiceImpl<GatherAmmeterMapper, GatherAmmeter> implements IGatherAmmeterService {

    @Autowired
    private GatherAmmeterMapper gatherAmmeterMapper;

    @Autowired
    private IGatherService gatherService;

    @Autowired
    private IAssetsAmmeterService ammeterService;

    @Override
    public void mount(Long gatherId, String ids) {
        if (gatherId==null){
            throw new LogicException("采集信息ID不能为空");
        }
        String[] split = ids.split(",");

        //先删除之前的挂接
        QueryWrapper<GatherAmmeter> qw = new QueryWrapper<>();
        qw.eq("gather_id",gatherId);
        gatherAmmeterMapper.delete(qw);

        //批量添加
        for (int i = 0; i < split.length; i++) {
            GatherAmmeter ga = new GatherAmmeter();
            ga.setGatherId(gatherId);
            ga.setAmmeterId(Long.parseLong(split[i]));
            gatherAmmeterMapper.insert(ga);
        }

        //将挂接数量添加到采集表中
        gatherService.update(new UpdateWrapper<Gather>().set("ammeter_number",split.length).eq("id",gatherId));

    }

    @Override
    public List<AssetsAmmeter> mountList(Long gatherId) {
        List<AssetsAmmeter> list = new ArrayList<>();//定义存在电表的集合
        //查询关联表中已经挂接的电表
        List<GatherAmmeter> gather = gatherAmmeterMapper.selectList(new QueryWrapper<GatherAmmeter>().eq("gather_id", gatherId));
        //循环遍历 通过电表id查询电表表中的数据 将数据放进集合
        for (GatherAmmeter gatherAmmeter : gather) {
            list.add(ammeterService.getOne(new QueryWrapper<AssetsAmmeter>().eq("id",gatherAmmeter.getAmmeterId())));
        }
        return list;
    }
}
